#!/usr/bin/env python
# coding=UTF-8
import copy
import datetime
import json
import logging
import random
import time
import urllib

from nsq.http import nsqd
import redisco
from redisco.containers import List, Hash

import config
import dao


class YgMajiang():
    def __init__(self, rid, bid, dealer=None):
        self.rid = str(rid)
        if dealer:
            redisco.connection.delete("r:%s:current_card" % rid)
            redisco.connection.delete("r:%s:out_card" % rid)
            # redisco.connection.delete("r:%s" % rid)
            redisco.connection.delete("r:%s:mid" % rid)
            self.room = Hash("r:%s" % rid)
            self.room['dealer'] = dealer
            self.room['last_get_user'] = dealer
            self.room['last_put_user'] = ''
            self.room['dark_bar_joker'] =''
            #game_round = int(self.room.get('game_round', 0))
            #self.room['game_round'] = game_round + 1
            self.room['stop_pop_user'] = ''
            self.room['stop_pop_act'] = ''
            self.room['loser'] = ''
            self.room['last_card'] = ''
            self.room['joker'] = ''
        else:
            self.room = Hash("r:%s" % rid)
        self.current_card = List("r:%s:current_card" % rid)
        self.out_card = List("r:%s:out_card" % rid)
        self.tips_user = List("r:%s:tips_user" % rid)
        self.tips_act = List("r:%s:tips_act" % rid)
        self.winner = List("r:%s:winner" % rid)
        self.bid = bid
        l = List("r:%s:p" % rid)
        self.members = l.members
    def incr_mid(self):
        return redisco.connection.incr("r:%s:mid" % self.rid)
    
    def start(self):
        self.room['status'] = 'start'
        w = [str(x) for x in range(11, 20)] * 4
        d = [str(x) for x in range(21, 30)] * 4
        t = [str(x) for x in range(31, 40)] * 4
        f = [str(x) for x in range(41, 48)] * 4
        random.shuffle(w)
        random.shuffle(d)
        random.shuffle(t)
        random.shuffle(f)
        player_cnt = len(self.members)
        init_left_card = 136 - player_cnt * 13 - 1
        #f = [str(x) for x in range(41, 48)]
        #f = f + sorted(f * 3)
        all_card = w + d + t + f 
        init_left_card -= 24
        random.shuffle(all_card)
        
        dealer_seat = self.members.index(self.room['dealer'])
        for i in range(player_cnt):
            idex = (dealer_seat + i) % player_cnt
            uid = self.members[idex]
            player = Player(uid, self.bid,self.rid, True)
            card = []
            for i in range(13):
                card.append(all_card.pop())
                card.sort()
            player.current_card.extend(card)
            mid = self.incr_mid()
            nsq_pub({"b":self.bid, "u":str(uid), "t":"game", "d":{"left_card":init_left_card, "rid":self.rid, "mid":mid, "act":"game_start", "dealer":self.room['dealer'], "card":card, "game_round":self.room['game_round'], "all_round":self.room['all_round']}})
        dealer = self.room['dealer']
        self.room['last_get_user'] = dealer
        self.current_card.clear()
        self.current_card.extend(all_card)
        logging.info(u"房间rid:%s,game_round:%s,开始发牌: %s" % (self.rid, self.room['game_round'], str(self.current_card.members)))
        self.joker_pop()
        #发包牌
        self.next_pop(dealer)
        
        
     
    '''宝牌发牌逻辑'''
    def joker_pop(self):
        jokerstr = self.current_card.pop()
        self.current_card.append(jokerstr)
        joker = int(jokerstr)
        if joker==19 or joker==29 or joker==39 or joker==47:
            joker=(joker/10)*10+1
        else:
            joker = joker+1
        mid = self.incr_mid()
        self.room['joker'] = str(joker)
        for member in self.members:
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"joker_put", "rid":self.rid,"joker":str(joker)}})
    
    """发牌逻辑"""
    def next_pop(self, uid=None, from_bar=False):
        self.tips_act.clear()
        self.tips_user.clear()
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        if not uid:
            last_get_user = self.room['last_get_user']
            logging.info("next_pop, last:%s" % last_get_user)
            last_player_seat = self.members.index(str(last_get_user))
            idx = (last_player_seat + 1) % len(self.members)
            uid = self.members[idx]
        
        left_card = len(self.current_card.members)
        horse_num = int(self.room['horse'])
        if left_card <= horse_num:
            logging.info(u"房间%s剩余牌数小于马牌数量，结束牌局" % (str(left_card)))
            self.game_over()
            return
        card = self.current_card.pop()
        if not card:
            logging.info("over===========")
            self.game_over()
            return
        
        p = Player(uid, self.bid, self.rid)
        
        self.room['last_get_user'] = uid
        self.room['last_card'] = card
        if from_bar:
            self.room['bar_get_card'] = card
        else: 
            self.room['bar_get_card'] = ''
            
        p.tips.clear()
        #检查漏胡标记, 摸牌后清除状态
        p_flag = p.score['flag']
        if p_flag == 'n':
            p.score['flag'] = ''
        tips = []
        bar_card = []
        pair_bar_card = []
        win_type = self.check_win(p, card)
        if win_type:
            tips.append("win")
        
        current_card = p.current_card.members
        init_dark_bar = self.check_init_dark_bar(current_card)
        if self.check_bar(current_card, card):
            tips.append("dark_bar")
            bar_card.append(card)
        elif self.check_pair_bar(p.pair.members, card):
            tips.append("pair_bar")
        if init_dark_bar:
            tips.append("dark_bar")
            bar_card.extend(init_dark_bar)
        user_data = p.get_data()
        p.current_card.append(card)
        #在手中任然可以杠提示
        if self.check_out_pair_bar(p.pair.members,p.current_card.members):
            tips.append("out_pair_bar")
            pair_bar_card.extend(pair_bar_card)
        mid = self.incr_mid()
        left_card = len(self.current_card)
        
        if tips:
            self.room['stop_pop_user'] = uid
            self.room['stop_pop_act'] = ",".join(tips)
        for member in self.members:
            nsq_pub({"b":self.bid, "u":member, "t":"game", "d":{"act":"get_card", "left_card":left_card, "uid":uid, "card":card, "rid":self.rid,"tips":tips,"bar_card":bar_card,"pair_bar_card":pair_bar_card}})
        
        game_round = self.room['game_round']
        nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"act":"get_card", "game_round":game_round,"left_card":left_card, "mid":mid, "uid":uid, "card":card, "rid":self.rid, "user_data":user_data,"tips":[]}})

        logging.info("通知发牌：%s"%tips)
        if tips:
             self.tips_user.append(uid)
             self.tips_act.extend(tips)
             p.tips.extend(tips)
        else:
            logging.info("通知发牌。。。。。。。。。。。。")
            self.notify_put(uid)
    
    def notify_put(self, uid):
        '''通知玩家出牌'''
        self.room['last_get_user'] = uid
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        mid = self.incr_mid()
        for member in self.members:
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"turn_put", "rid":self.rid, "uid":uid}})
    
    def check_pair_bar(self, pair, card=''):
        # 检查碰过的牌是否摸到杠
        if pair.count(card) >= 1:
            return True
        return False
    
        
    
    def notify_tips(self, uid, card, tips, bar_card=[], eat_card=[],pair_bar_card=[]):
        #self.room['stop_pop_user'] = ""
        #self.room['stop_pop_act'] = ""
        nsq_pub({"b":self.bid, "u":str(uid), "t":"game", "d":{"act":"tips", "rid":self.rid, "uid":uid, "tips":tips, "card":card, "bar_card":bar_card, "eat_card":eat_card, "pair_bar_card":pair_bar_card}})
        
    """出牌逻辑"""
    def put_card(self, uid, data):
        # 玩家出牌逻辑
        uid = str(uid)
        #是否重复发牌给客户端
        stop_pop_user = self.room['stop_pop_user']
        if stop_pop_user and stop_pop_user != str(uid):
            logging.error(u"玩家:%s有提示未处理,轮不到%s出牌" % (stop_pop_user, uid))
            get_last_data(self.bid, uid, self.rid)
            return
        last_put_user = self.room['last_put_user']
        if uid == last_put_user:
            logging.error(u"玩家:%s不能连续出牌" % (uid))
            get_last_data(self.bid, uid, self.rid)
            return
        card = data['card']
        p = Player(uid, self.bid, self.rid)
        #飞宝
        if card==self.room['joker']:
            p.score["put_joker_count"] = str(int(p.score["put_joker_count"])+1)
            
        curernt_card = p.current_card.members
        logging.info("put_card======当前uid:%s,current_card:%s"%(uid,curernt_card))
        if curernt_card.count(card) == 0:
            logging.info(curernt_card)
            logging.error(u"出牌错误,该玩家没有该牌")
            get_last_data(self.bid, uid, self.rid)
            return
        
        #self.tips_act.clear()
        #self.tips_user.clear()
        
        p.out_card.append(card)
        p.current_card.remove(card)
        self.room['last_put_user'] = uid
        self.room['last_get_user'] = uid
        self.room['last_card'] = card
        
        p.score['put_flag'] = 'y'
        members = self.members
        player_cnt = len(members)
        mid = self.incr_mid()
        put_win_user = []
        #按照玩家座位顺序检查是否有胡牌可能
        user_seat = members.index(uid)
        tips = []
        self.room['bar_get_card'] = ''
        user_data = p.get_data()
        for i in range(player_cnt):
            idex = (user_seat + i) % player_cnt
            member = members[idex]
            win_card = []
            nsq_pub({"b":self.bid, "u":member, "t":"game", "d":{"act":"put_card", "win_card":win_card, "card":card, "rid":self.rid, "uid":uid,"tips":[]}})

        for i in range(player_cnt):
            idex = (user_seat + i) % player_cnt
            member = members[idex]
            if member != uid:
                member_player = Player(member, self.bid, self.rid)
                if self.check_win(member_player, card):
                    put_win_user.append(member)
                    member_player.tips.append("put_win")
        
        if put_win_user:
            #点炮胡的情况
            self.room['stop_pop_user'] = ",".join(put_win_user)
            self.room['stop_pop_act'] = "put_win"
            tips = ["put_win",]
            mid = self.incr_mid()
            self.tips_user.extend(put_win_user)
            self.tips_act.extend(tips)
            win_user = put_win_user[0]
            logging.info("推送win_user消息：%s",tips)
            self.notify_tips(win_user, card, tips, [], [],[])
            return
        game_round = self.room['game_round']
        nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"act":"put_card", "game_round":game_round,"win_card":win_card, "mid":mid, "card":card, "rid":self.rid, "uid":uid, "user_data":user_data}})
        res = self.check_pair_tips(uid, card)
        if res:
            return
        eat_user = self.check_eat_tips(uid, card)
        if eat_user:
            return
        #所有提示都没有的情况,继续下家发牌
        self.next_pop()
        
        
    def check_eat_tips(self,last_put_user='', card=''):
        if not last_put_user:
            last_put_user = self.room['last_put_user']
            last_put_player = Player(last_put_user, self.bid, self.rid)
            card = last_put_player.out_card.members[-1]
        members = self.members
        user_seat = members.index(last_put_user)
        next_idex = (user_seat + 1) % len(members)
        next_member = members[next_idex]
        next_player = Player(next_member, self.bid, self.rid)
        next_player_card = next_player.current_card.members
        eat_card_list = self.get_eat_card(next_player_card, card)
        if eat_card_list and self.room['jiazi']=='n':
            tips = ['eat',]
            self.room['stop_pop_user'] = next_member
            self.room['stop_pop_act'] = ",".join(tips)
            self.tips_user.append(next_member)
            self.tips_act.extend(tips)
            next_player.tips.extend(tips)
            mid = self.incr_mid()
            nsq_pub({"b":self.bid, "u":next_member, "t":"game", "d":{"act":"tips", "mid":mid, "card":card, "tips":tips, "rid":self.rid, "uid":next_member, "eat_card":eat_card_list}})
            return next_member
        return False
            
        
    def check_pair_tips(self, last_put_user='', card=''):
        if not last_put_user:
            last_put_user = self.room['last_put_user']
            last_put_player = Player(last_put_user, self.bid, self.rid)
            card = last_put_player.out_card.members[-1]
        
        members = self.members
        user_seat = members.index(last_put_user)
        next_idex = (user_seat + 1) % len(members)
        next_member = members[next_idex]
        tips_user = []
        eat_card_list = []
        for member in members:
            if member != last_put_user:
                member_player = Player(member, self.bid, self.rid)
                current_card = member_player.current_card.members
                tips = [] 
                logging.info(u"提示检查：手牌：%s,出牌：%s"%(current_card,card))
                if self.check_bar(current_card, card):
                    tips.append("bar")
                    tips.append("pair")
                elif self.check_pair(current_card, card):
                    tips.append("pair")
                
                if tips and member == next_member:
                    eat_card_list = self.get_eat_card(current_card, card)
                    if eat_card_list and self.room["jiazi"]=="n":
                        tips.append("eat")
                else:
                    eat_card_list = []

                if tips:
                    tips_user.append(member)
                    self.tips_user.append(member)
                    self.tips_act.extend(tips)
                    member_player.tips.extend(tips)
                    self.room['stop_pop_user'] = member
                    self.room['stop_pop_act'] = ",".join(tips)
                    logging.info("推送tips消息======：%s，pop_user:%s,"%(tips,member))
                    self.notify_tips(member, card, tips, [], eat_card_list,[])
                    logging.info(u"房间%s玩家%s出牌%s,%s通知提示" % (self.rid, last_put_user, card, member))
            
        return tips_user
    
     
    
    def pass_card(self, uid, data):
        logging.info("pass:%s,tips_user:%s" % (uid,self.tips_user))
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.error(u"目前没有提示, 不该%s操作" % uid)
            return
        elif uid not in stop_pop_user.split(","):
            logging.error(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        last_put_user = self.room['last_put_user']
        stop_pop_act = self.room['stop_pop_act']
        p = Player(last_put_user, self.bid, self.rid)
        self.tips_user.remove(uid)
        card = p.out_card.members[-1]
        if "put_win" in stop_pop_act:
            p.score['flag'] = 'n'
            stop_pop_user_list = stop_pop_user.split(",")
            idx = stop_pop_user_list.index(uid)
            if len(stop_pop_user_list) != (idx+1):
                #给下一家可胡牌玩家推送通知
                next_player = stop_pop_user_list[idx+1]
                mid = self.incr_mid()
                tips = ["put_win",]
                nsq_pub({"b":self.bid, "u":str(next_player), "t":"game", "d":{"mid":mid, "act":"tips", "card":card, "tips":tips, "rid":self.rid, "uid":uid}})
                return
            else:
                #所有可点炮胡的玩家都通知完
                self.room['stop_pop_user'] = ""
                self.room['stop_pop_act'] = ""
                tips_user = self.check_pair_tips(last_put_user, card)
                if tips_user:
                    logging.info(u"%s:pass, 有其他玩家%s要碰牌或杠" % (uid, tips_user))
                    return
                tips_user = self.check_eat_tips(last_put_user, card)
                if tips_user:
                    logging.info(u"点炮胡玩家%s:pass, 有其他玩家:%s要吃牌" % (uid, tips_user))
                    return
        elif "bar_win" in stop_pop_act:
            self.room['stop_pop_user'] = ""
            self.room['stop_pop_act'] = ""
            last_get_user = self.room['last_get_user']
            self.next_pop(last_get_user, True)
            return
        
        elif "pair" in stop_pop_act or "bar" in stop_pop_act:
            self.room['stop_pop_user'] = ""
            self.room['stop_pop_act'] = ""
            if "eat" not in stop_pop_act:
                tips_user = self.check_eat_tips(last_put_user, card)
                if tips_user:
                    logging.info(u"碰,杠玩家%s:pass, 有其他玩家:%s要吃牌" % (uid, tips_user))
                    return
        
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        
        if self.room['last_get_user'] != uid:
            self.next_pop()
        else:
            self.notify_put(uid)

                

    def get_eat_card(self, all_card, card):
        '''获取可吃的牌'''
        logging.info(u"吃牌检查,手牌：%s,出牌：%s" % (all_card,card))
        card = int(card)
        if card > 40:
            return []
        c = card % 10
        n = card / 10
        res = []
        point_res = []
        if c == 9:
            point_res = [[7, 8]]
        elif c == 8:
            point_res = [[6, 7], [7, 9]]
        elif c == 7:
            point_res = [[5, 6], [6, 8], [8, 9]]
        elif c == 6:
            point_res = [[4, 5], [5, 7], [7, 8]]
        elif c == 5:
            point_res = [[3, 4], [4, 6], [6, 7]]
        elif c == 4:
            point_res = [[2, 3], [3, 5], [5, 6]]
        elif c == 3:
            point_res = [[1, 2], [2, 4], [4, 5]]
        elif c == 2:
            point_res = [[1, 3], [3, 4]]
        elif c == 1:
            point_res = [[2, 3]]
        for [s, e] in point_res:
            c1 = str(n*10+s)
            c2 = str(n*10+e)
            if c1 in all_card and c2 in all_card:
                res.append([c1, c2])
        return res
    
    def dark_bar(self, uid, data):
        tips_user = self.tips_user.members
        if not tips_user:
            logging.error(u"目前没有提示, 不该%s操作" % uid)
            get_last_data(self.bid, uid, self.rid)
            return
        elif uid not in tips_user:
            logging.error(u"玩家%s有提示, 不该%s操作" % (str(tips_user), uid))
            get_last_data(self.bid, uid, self.rid)
            return
        
        card = data.get('card', '')
        p = Player(uid, self.bid, self.rid)
        #4宝
        if card == self.room["joker"]:
            self.room["dark_bar_joker_uid"] = uid
        current_card = p.current_card.members
        if not card:
            for k in set(current_card):
                if current_card.count(k) == 4:
                    card = k
        else:
            if not self.check_dark_bar(current_card, card):
                logging.error(u"请求错误,该用户不能杠牌:%s" % card)
                get_last_data(self.bid, uid, self.rid)
                return
        p.current_card.remove(card, 4)
        p.dark_bar.append(card)
        
        p.tips.clear()
        self.tips_user.clear()
        self.tips_act.clear()
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        mid = self.incr_mid()
        for member in self.members:
            nsq_pub({"b":self.bid, "u":member, "t":"game", "d":{"act":"dark_bar", "card":card, "tips":[], "rid":self.rid, "uid":uid}})
        user_data = p.get_data()
        game_round = self.room['game_round']
        nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"act":"dark_bar", "game_round":game_round,"mid":mid, "card":card, "tips":[], "rid":self.rid, "uid":uid, "user_data":user_data}})
        
        self.next_pop(uid)
        
    def pair_bar(self, uid, data):
        # 碰过别的牌, 然后自己摸到一张，没有分
        # card = data['card']
        tips_user = self.tips_user.members
        if not tips_user:
            logging.error(u"目前没有提示, 不该%s操作" % uid)
            get_last_data(self.bid, uid, self.rid)
            return
        elif uid not in tips_user:
            logging.error(u"玩家%s有提示, 不该%s操作" % (str(tips_user), uid))
            get_last_data(self.bid, uid, self.rid)
            return

        p = Player(uid, self.bid, self.rid)
        card = p.current_card.members[-1]
        if not self.check_pair_bar(p.pair.members, card):
            logging.error(u"请求错误,该用户不能杠牌:%s" % card)
            get_last_data(self.bid, uid, self.rid)
            return
        #杠宝
        if card == self.room["joker"]:
            joker_bar = p.score["joker_bar"]
            p.score["joker_bar"] = joker_bar+1
        
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        p.current_card.remove(card)
        p.pair.remove(card)
        #p.white_bar.append(card)
        
        #pair_users = p.pair_user
#         for pu in pair_users:
#             arr = pu.split(",")
#             if arr[0]==card:
        p.pair_bar_user.append(uid)
        p.tips.clear()
        self.tips_user.clear()
        self.tips_act.clear()
        
        self.room['last_get_user'] = uid
        self.room['last_card'] = card
        mid = self.incr_mid()
        tips = []
        user_data = p.get_data()
        for member in self.members:
            nsq_pub({"b":self.bid, "u":member, "t":"game", "d":{"act":"pair_bar", "card":card, "tips":[], "rid":self.rid, "uid":uid}})
        
        game_round = self.room['game_round']
        nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"act":"pair_bar", "game_round":game_round,"mid":mid, "card":card, "tips":[], "rid":self.rid, "uid":uid, "user_data":user_data}})
        bar_win_user = []
        for member in self.members:
            if member != uid:
                member_player = Player(member, self.bid, self.rid)
                tips = []
                if self.room['grab_bar_win'] == 'y':
                    if self.check_win(member_player, card):
                        bar_win_user.append(member)
        
        if bar_win_user:
            #点炮胡的情况
            self.room['stop_pop_user'] = ""
            self.room['stop_pop_act'] = ""
            tips = ["pair_bar_win"]
            self.tips_user.extend(bar_win_user)
            self.tips_act.extend(tips)
            for win_user in bar_win_user:
                self.notify_tips(win_user, card, tips, [], [],[])
            return
        else:
            self.next_pop(uid, from_bar=True)
    
    def check_dark_bar(self, current_card, card=''):
        # 检查摸的牌能否暗杠
        if current_card.count(card) == 4:
            return True
        return False
    
    def bar(self, uid, data):
        # 自己有三张,直接杠别人出的牌
        # card = data['card']
        # bar_uid = data['put_card_uid']
        
        tips_user = self.tips_user.members
        if not tips_user:
            logging.error(u"目前没有提示, 不该%s操作" % uid)
            get_last_data(self.bid, uid, self.rid)
            return
        elif uid not in tips_user:
            logging.error(u"玩家%s有提示, 不该%s操作" % (str(tips_user), uid))
            get_last_data(self.bid, uid, self.rid)
            return
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid, self.rid)
        
        card = last_put_player.out_card.members[-1]
        p = Player(uid, self.bid, self.rid)
        current_card = p.current_card.members
        if not self.check_bar(current_card, card):
            logging.error(u"请求错误,该用户不能杠牌:%s" % card)
            get_last_data(self.bid, uid, self.rid)
            return
        p.score['put_flag'] = 'y'
        card = last_put_player.out_card.pop()
        p.current_card.remove(card, 3)
        p.white_bar.append(card)
        p.bar_user.append(last_put_user)
        if card == self.room["joker"]:
            p.score["joker_bar"] = p.score["joker_bar"]+1
        p.tips.clear()
        self.tips_user.clear()
        self.tips_act.clear()
        mid = self.incr_mid()
        self.room['last_get_user'] = uid
        self.room['last_card'] = card
        user_data = p.get_data()
        for member in self.members:
            nsq_pub({"b":self.bid, "u":member, "t":"game", "d":{"act":"bar", "card":card, "rid":self.rid, "uid":uid, "put_card_uid":last_put_user, "user_data":{}}})
        
        game_round = self.room['game_round']
        nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"act":"bar", "game_round":game_round,"mid":mid, "card":card, "rid":self.rid, "uid":uid, "put_card_uid":last_put_user, "user_data":user_data}})
        
        bar_win_user = []
        for member in self.members:
            if member != uid:
                member_player = Player(member, self.bid, self.rid)
                tips = []
                if member in tips_user:
                    member_player.tips.clear()
                if self.room['grab_bar_win'] == 'y':
                    if self.check_win(member_player, card):
                        bar_win_user.append(member)
        
        if bar_win_user:
            #点炮胡的情况
            self.room['stop_pop_user'] = ""
            self.room['stop_pop_act'] = ""
            tips = ["pair_bar_win"]
            self.tips_user.extend(bar_win_user)
            self.tips_act.extend(tips)
            for win_user in bar_win_user:
                self.notify_tips(win_user, card, tips, [], [],[])
            return
        else:
            self.next_pop(uid, from_bar=True)

    def pair(self, uid, data):
        tips_user = self.tips_user.members
        if not tips_user:
            logging.error(u"目前没有提示, 不该%s操作" % uid)
            get_last_data(self.bid, uid, self.rid)
            return
        elif uid not in tips_user:
            logging.error(u"玩家%s有提示, 不该%s操作" % (str(tips_user), uid))
            get_last_data(self.bid, uid, self.rid)
            return
        # card = data['card']
        # put_card_uid = data['put_card_uid']
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid, self.rid)
        card = last_put_player.out_card.members[-1]
        
        p = Player(uid, self.bid, self.rid)
        #碰宝
        if card==self.room["joker"]:
            p.score["put_joker_count"]= str(int(p.score["put_joker_count"])+2)
        current_card = p.current_card.members
        if not self.check_pair(current_card, card):
            logging.error(u"请求错误,该用户不能碰牌:%s" % card)
            get_last_data(self.bid, uid, self.rid)
            return
        card = last_put_player.out_card.pop()
        p.score['put_flag'] = 'y'
        p.current_card.remove(card, 2)
        p.pair.append(card)
        
        self.tips_user.clear()
        self.tips_act.clear()
        p.tips.clear()
        
        user_data = p.get_data()
        mid = self.incr_mid()
        for member in self.members:
            if member in tips_user:
                member_player = Player(member, self.bid, self.rid)
                member_player.tips.clear()
            nsq_pub({"b":self.bid, "u":member, "t":"game", "d":{"act":"pair", "card":card, "rid":self.rid, "uid":uid, "put_card_uid":last_put_user, "user_data":{}}})
        
        game_round = self.room['game_round']
        nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"act":"pair", "game_round":game_round, "mid":mid, "card":card, "rid":self.rid, "uid":uid, "put_card_uid":last_put_user, "user_data":user_data}})
        self.room['last_get_user'] = uid
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        self.notify_put(uid)


    def eat(self, uid, data):
        '''吃牌'''
        tips_user = self.tips_user.members
        if not tips_user:
            logging.error(u"目前没有提示, 不该%s操作" % uid)
            get_last_data(self.bid, uid, self.rid)
            return
        elif uid not in tips_user:
            logging.error(u"玩家%s有提示, 不该%s操作" % (str(tips_user), uid))
            get_last_data(self.bid, uid, self.rid)
            return
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid, self.rid)
        card = last_put_player.out_card.members[-1]
        
        p = Player(uid, self.bid, self.rid)
        current_card = p.current_card.members
        eat_card_list = self.get_eat_card(current_card, card)
        if not eat_card_list:
            logging.error(u"请求错误,该用户不能吃这张牌:%s" % card)
            get_last_data(self.bid, uid, self.rid)
            return
        if len(tips_user) > 1:
            p.score['eat_data'] = json_encode(data)
            self.room['stop_pop_user'] = uid
            self.room['stop_pop_act'] = "eat"
            return
        p.tips.clear()
        
        self.do_eat(uid, data)
    
    def do_eat(self, uid, data):
        '''吃牌'''
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid, self.rid)
        card = last_put_player.out_card.members[-1]
        
        p = Player(uid, self.bid, self.rid)
        current_card = p.current_card.members
        eat_card_list = self.get_eat_card(current_card, card)
        if not eat_card_list:
            logging.error(u"请求错误,该用户不能吃这张牌:%s" % card)
            get_last_data(self.bid, uid, self.rid)
            return
        
        eat_card = data['eat_card']
        logging.info(u"========================吃牌 eat_card：%s"%eat_card)
        c1 = eat_card[0]
        c2 = eat_card[1]
        if c1 not in current_card or c2 not in current_card or not self.check_eat(eat_card, card):
            logging.error(u"吃牌错误,该用户%s不能吃这张牌:%s" % (uid, card))
            get_last_data(self.bid, uid, self.rid)
            return
        self.tips_user.clear()
        self.tips_act.clear()
        
        card = last_put_player.out_card.pop()
        p.current_card.remove(eat_card[0], 1)
        p.current_card.remove(eat_card[1], 1)
        logging.info(u"吃牌：%s,玩家：%s,房间：%s,吃完牌为：%s,eat_card[0]:%s,eat_card[1]:%s"%(p.eat,uid,self.rid,p.current_card.members,eat_card[0],eat_card[1]))
        p.score['put_flag'] = 'y'
        eat_card_list = [c1, c2, card]
        eat_card_list.sort()
        p.eat.append(",".join(eat_card_list))
        logging.info(u"吃牌：%s,玩家：%s,房间：%s"%(p.eat,uid,self.rid))
        mid = self.incr_mid()
        user_data = p.get_data()
        for member in self.members:
            nsq_pub({"b":self.bid, "u":member, "t":"game", "d":{"act":"eat", "card":card, "eat_card":eat_card_list, "rid":self.rid, "uid":uid, "put_card_uid":last_put_user, "user_data":{}}})
        
        game_round = self.room['game_round']
        nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"act":"eat", "game_round":game_round,"mid":mid, "card":card, "eat_card":eat_card_list, "rid":self.rid, "uid":uid, "put_card_uid":last_put_user, "user_data":user_data}})
        
        self.room['last_get_user'] = uid
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        self.notify_put(uid)
            
            
    def check_win(self, player, card=''):
        '''检查是否符合自模糊'''
        # 检查
        n = 0
        dark_bar = player.dark_bar.members
        white_bar = player.white_bar.members
        pair = player.pair.members
        eat = player.eat.members
        n += len(dark_bar)
        n += len(white_bar)
        n += len(pair)
        n += len(eat)
        logging.info("暗杠：%s,明杠：%s,碰：%s,吃：%s"%(dark_bar,white_bar,pair,eat))
        current_card = player.current_card.members
        if card:
            current_card.append(card)
        joker = self.room['joker']
        if joker:
            joker_list = joker.split(",")
        else:
            joker_list = []
        logging.info(u"判断用户%s是否胡牌:%s,癞子:%s" % (player.uid, str(current_card),joker_list))
        if self.check_seven_pairs(current_card,joker_list):
            logging.info(u"十三烂胡牌检查，手牌：%s，癞子:%s"%(current_card,joker_list))
            return True
        elif self.check_shisanlan(current_card, joker):
            logging.info(u"七小队胡牌检查，手牌：%s,癞子：%s"%(current_card,joker_list))
            return True
        
        if len(current_card) != ((4 - n) * 3 + 2):
            logging.info(u"该玩家手牌相公不能胡牌:%s" % player.uid)
            return False
        elif self.is_pinghu(current_card, n, 'win', joker_list):
            return True
        
        return False
    
    
    def check_eat(self, all_card, card):
        '''判断能否吃card牌'''
        card = int(card)
        all_card = [int(x) for x in all_card]
        all_card.append(card)
        all_card.sort()
        if card<40 and len(all_card) == 3 and (all_card[0]+1) == all_card[1] and (all_card[0]+2) == all_card[2]:
            return True
        return False       
    
    def check_pair(self, current_card, card=''):
        # 检查能否碰牌
        if current_card.count(card) >= 2:
            return True
        return False
    
#     def is_pengpenghu(self, all_card, has_n=0):
#         '''碰碰胡,AAABBBCCCDDD乱将'''
#         res = [0]
#         jiang_list = self.get_jiang(all_card)
#         for jiang in jiang_list:
#             card = self.trans_card(all_card)
#             card.remove(jiang)
#             card.remove(jiang)
#             triple = 0
#             for c in set(card):
#                 if card.count(c) == 3:
#                     triple += 1
#             res.append(triple+1)
#         if max(res)+has_n >= 5:
#             return 'pengpenghu'
#         return False
    
#     def is_qixiaodui(self, all_card,joker_list=[]):
#         '''七小对'''
#         pair = 0
#         bomb = 0
#         card = self.trans_card(all_card)
#         for c in set(card):
#             if card.count(c) == 4:
#                 bomb += 1
#                 pair += 2
#             elif card.count(c) == 2:
#                 pair += 1
#         if pair == 7:
#             if bomb == 2:
#                 '''双豪华七小对'''
#                 return 'two_qixiaodui'
#             elif bomb ==3:
#                 '''三豪华七对'''
#                 return 'three_qixiaodui'
#             elif bomb == 1:
#                 '''豪华七小对'''
#                 return 'one_qixiaodui' 
#             return 'qixiaodui'
#         return False
    
    def check_put_win(self, player, card='', joker_list=[]):
        '''点炮胡检查'''
        n = 0
        dark_bar = player.dark_bar.members
        white_bar = player.white_bar.members
        pair = player.pair.members
        eat = player.eat.members
        n += len(dark_bar)
        n += len(white_bar)
        n += len(pair)
        n += len(eat)
        current_card = player.current_card.members
        if card:
            current_card.append(card)
        if len(current_card) != ((4 - n) * 3 + 2):
            logging.info(u"该玩家手牌相公不能胡牌:%s" % player.uid)
            return False
        if self.is_qixiaodui(current_card):
            return True
#         elif self.is_pengpenghu(current_card, len(pair)+len(dark_bar)+len(white_bar)):
#             return True
        all_card = []
        all_card.extend(current_card)
        if dark_bar:
            all_card.extend(dark_bar)
        if white_bar:
            all_card.extend(white_bar)
        if pair:
            all_card.extend(pair)
        if eat:
            for eat_card in eat:
                all_card.extend(eat_card.split(","))
        putcard_isjoker = False
        if joker_list.count(card)>0:
            putcard_isjoker = True
        if self.is_pinghu(current_card, n, "put_win",joker_list,putcard_isjoker):
            return True
        return False
    
    def is_pinghu(self, all_card, has_n=0, win_type='put_win', joker_list=[],putcard_isjoker=False):
        '''平胡'''
        mj = MaJiangCheck()
        res = mj.check_win(has_n, all_card, '', joker_list)
        if res:
            return 'pinghu'
        return False

    #是否夹子胡法
    def check_jiazi(self, player, card=''):
        n = 0
        dark_bar = player.dark_bar.members
        white_bar = player.white_bar.members
        pair = player.pair.members
        eat = player.eat.members
        n += len(dark_bar)
        n += len(white_bar)
        n += len(pair)
        n += len(eat)
        current_card = player.current_card.members
        if card:
            current_card.append(card)
        if len(current_card) != ((4 - n) * 3 + 2):
            logging.info(u"该玩家手牌相公不能胡牌:%s" % player.uid)
            return False
    
        joker = self.room['joker']
        if joker:
            joker_list = joker.split(",")
        else:
            joker_list = []
            
        all_card = []
        all_card.extend(current_card)
        if dark_bar:
            all_card.extend(dark_bar)
        if white_bar:
            all_card.extend(white_bar)
        if pair:
            all_card.extend(pair)
        if eat:
            for eat_card in eat:
                all_card.extend(eat_card.split(","))
        mj = MaJiangCheck()
        card_list = self.trans_card(current_card);
        logging.info("牌列表：%s,n:%s,joker:%s"%(card_list,n,joker))
        if int(card)%10==7:
            card1 = int(card)+1
            card2 = int(card)+2
            card3 = int(card)-1
            logging.info("card1：%s,card1:%s"%(card1,card2))
            if card_list.count(card1)>0 and card_list.count(card2)>0:
                card_list.remove(card1)
                card_list.remove(card2)
            elif card_list.count(card1)>0 and card_list.count(card3)>0:
                card_list.remove(card1)
                card_list.remove(card3)
            else:
                return False
        elif int(card)%10 == 3:
            card1 = int(card)-1
            card2 = int(card)-2
            card3 = int(card)+1
            logging.info("===card1：%s,card1:%s"%(card1,card2))
            if card_list.count(card1)>0 and card_list.count(card2)>0:
                card_list.remove(card1)
                card_list.remove(card2)
            elif card_list.count(card1)>0 and card_list.count(card3)>0:
                card_list.remove(card1)
                card_list.remove(card3)
            else:
                return False
        else:
            card1 = int(card)-1
            card2 = int(card)+1
            logging.info("==card1：%s,card1:%s"%(card1,card2))
            if card_list.count(card1)>0 and card_list.count(card2)>0:
                card_list.remove(card1)
                card_list.remove(card2)
            else:
                return False
        n = n + 1
        card_list.remove(int(card))
        logging.info("card_list============：%s，joker:%s,n:%s"%(card_list,joker_list,n))

        return mj.check_win(n, card_list, '', joker_list)
        
            
    def is_qingyise(self, all_card,joker=[]):
        '''清一色:240'''
        card = self.trans_card(all_card)
        joker_list = self.trans_card(joker)
        for j in joker_list:
            m = card.count(j)
            for i in range(m):
                card.remove(j)
        
        color = card[0]/10
        for c in set(card):
            if c/10 != color:
                return False
        return True
    
    '''获取麻将的所有可能的将的列表'''
    '''如果有癞子则所有的子都有可能为将'''
    '''如果没有来自则必须对子才能为将'''
    def get_jiang(self, card, joker_list=[]):
        r = []
        for k in set(card):
            if card.count(k) >= 2 or (joker_list and joker_list.count(k)!=1):
                r.append(k)
        r.sort()
        logging.info('手牌,joker_list:%s,cars:%s,将牌：%s'%(joker_list,card,r))
        return r
    
    def trans_card(self, all_card):
        return sorted([int(x) for x in all_card])
    
    
    def check_init_dark_bar(self, current_card):
        # 检查初始手牌能否暗杠
        res = []
        for k in set(current_card):
            if current_card.count(k) == 4:
                res.append(k)
        return res
    
    def check_out_pair_bar(self,pairs,current_card):
        res = []
        for k in set(current_card):
            for m in set(pairs):
                if m == k:
                    res.append(m)
        return res
    
    def check_bar(self, current_card, card=''):
        # 检查能否杠
        if current_card.count(card) == 3:
            return True
        return False
    
    #十三烂检查
    def check_shisanlan(self,all_card,joker=[]):
        card = self.trans_card(all_card)
        joker_list = self.trans_card(joker)
        if len(all_card)<14:
            return False
        for j in joker_list:
            m = card.count(j)
            for i in range(m):
                card.remove(j)
        for index in range(len(card)-1):
            c = card[index]
            cplus1 = card[index+1]
            if c<40:
                logging.info("c+1==%s",cplus1,"c=%s",c)
                if cplus1-c<=2 and c/10==cplus1/10:
                    return False
            else:
                if c==cplus1:
                    return False
        return True
    
    def check_qixing(self,all_card,joker=[]):
        card = self.trans_card(all_card)
        joker_list = self.trans_card(joker)           
        for j in joker_list:
            m = card.count(j)
            for i in range(m):
                card.remove(j)
        count = 0
        for num in range(41,48):
            if card.count(num)>0:
                count=count+1
        if count+m>=7:
            return True
        else:
            return False
            
        
    def get_seven_pairs(self, all_card, joker=[]):
        jiang_list = []
        joker_cnt = 0
        card = self.trans_card(all_card)
        joker_list = self.trans_card(joker)
        for j in joker_list:
            m = card.count(j)
            joker_cnt += m
            for i in range(m):
                card.remove(j)
        for c in set(card):
            if card.count(c) >= 2:
                jiang_list.append(c)
                for i in range(2):
                    card.remove(c)
        if not jiang_list:
            return 0
        return len(jiang_list) + joker_cnt
    
    def check_seven_pairs(self, all_card, joker_list=[]):
        '''七对胡'''
        pair_num = self.get_seven_pairs(all_card, joker_list)
        return pair_num == 7
    
    def get_seven_pairs_type(self,all_card,joker=[]):
        card = self.trans_card(all_card)
        joker_cnt = 0
        three_card = []
        four_card = []
        joker_list = self.trans_card(joker)
        pair_cnt = 0
        for j in joker_list:
            m = card.count(j)
            joker_cnt += m
            for i in range(m):
                card.remove(j)
        for c in set(card):
            if card.count(c)==3:
                three_card.append(c)
                pair_cnt = pair_cnt+1
                for i in range(3):
                    card.remove(c)
            if card.count(c)==4:
                four_card.append(c)
                pair_cnt = pair_cnt+2
                for i in range(4):
                    card.remove(c)
            if card.count(c)==2:
                pair_cnt = pair_cnt +1
                for i in range(2):
                    card.remove(c)
                    
        return len(four_card)+len(three_card)+(joker_cnt-len(three_card))/2
        
    def put_win(self, uid, data):
        #点炮胡
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.error(u"目前没有提示, 不该%s操作，stop_pop_user:%s" %(uid,stop_pop_user))
            get_last_data( self.bid, uid, self.rid)
            return
        elif uid not in stop_pop_user.split(","):
            logging.error(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            get_last_data( self.bid, uid, self.rid)
            return
        last_put_user = self.room['last_put_user']
        last_put_player = Player(last_put_user, self.bid, self.rid)
        card = last_put_player.out_card.members[-1]
        logging.info("last_put_user:%s, card:%s" % (last_put_user, card))
        p = Player(uid, self.bid, self.rid)
#         if not self.check_win(p, card):
#             logging.error(u"请求错误,该用户不能胡牌:%s" % card)
#             get_last_data( self.bid, uid, self.rid)
#             return
        win_score = 0
        win_type_list = self.get_win_type(p, card, win_type='put_win')
       
        if not win_type_list:
            get_last_data( self.bid, uid, self.rid)
            logging.error(u"请求错误,该用户不能胡牌:%s,win_type_list:%s" % (card,win_type_list))
            return
        else:
            win_score = self.get_win_score(win_type_list)
#             if p.dark_bar:
#                 win_score = win_score + len(p.dark_bar.members)*2*3
            logging.info(u"胡牌类型:%s，胡牌分：%s" %(win_type_list,win_score))
        data['card'] = card
        #for member in self.members:
        #    if member == uid:
        #        continue
        #    mid = self.incr_mid()
        #    nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"put_card", "card":card, "tips":[], "rid":self.rid, "uid":last_put_user}})
        
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
       
        #win_score = 2 * horse_num * (member_len - 1) + (member_len - 1)
        
        #grab_bar_duty = self.room['grab_bar_duty']
        
        win_score = win_score + self.getPutJokerScore(p.score["put_joker_count"], p.score["joker_bar"])
        jiazi = self.check_jiazi(p,card)
        logging.info("==================胡牌：是否为夹子%s"%jiazi)
        if jiazi:
            win_type_list.append("jiazi")
            win_score = win_score + self.get_win_score(["jiazi"])
        if last_put_user==self.room['dealer'] and len(last_put_player.out_card)==1:
            win_type_list.append("dihu")
            win_score= win_score + self.get_win_score(["dihu"])
        logging.info("胡牌列表============：%s",win_type_list)
        logging.info(u"基础分===========：%s"%win_score)
        dark_bar_joker_uid = self.room["dark_bar_joker_uid"]
        mid = self.incr_mid()
        dark_bark_count = 0
        pair_bar_count = 0
        for member in self.members:
            player = Player(member, self.bid, self.rid)
            play_score = int(player.score['score'])
            logging.info(u"胡牌：member:%s,uid:%s,last_put_user:%s"%(member,uid,last_put_user))
            if member != uid:
                if member == last_put_user:
                    play_score = play_score - win_score 
            #暗杠
            if player.dark_bar:
                play_score = play_score + 3*len(player.dark_bar)
                dark_bark_count = dark_bark_count + 1
            
            #暗杠宝
            if dark_bar_joker_uid:
                if dark_bar_joker_uid==member:
                    play_score = play_score + 60
                else:
                    play_score = play_score - 20
            #碰杠
            pair_bar_user = player.pair_bar_user
            logging.info(u"碰杠：%s,==================="%player.pair_bar_user)
            if pair_bar_user:
                play_score = play_score + 3*len(player.pair_bar_user)
                pair_bar_count = pair_bar_count + 1
            
            logging.info(u"明杠：%s,==================="%player.white_bar)
            #明杠
            white_bar = player.white_bar
            if white_bar:
                play_score= int(play_score)+len(player.white_bar)*1
                for wbu in player.bar_user:
                    white_bar_user = Player(wbu,self.bid,self.rid)
                    white_bar_user.score['score'] = int(white_bar_user.score['score']) - 1               
            player.score['score'] = play_score
        p.score['score'] = int(p.score['score']) + win_score
        for member in self.members:
            user = Player(member,self.bid,self.rid)
            logging.info(u"初始分：%s,碰杠数量：%s,暗杠数量：%s,pair_bar_count:%s,dark_bark_count:%s"%(user.score['score'],len(user.pair_bar_user),len(user.dark_bar),pair_bar_count,dark_bark_count))
            user.score['score'] = int(user.score['score']) - pair_bar_count*1 + len(user.pair_bar_user)*1 -dark_bark_count+len(user.dark_bar)
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"win", "card":card, "tips":[], "rid":self.rid, "uid":uid, "all_horse_card":[], "horse_card":[], "horse_num":0}})
        
        
        
        
        logging.info(u"=======================点炮胡：%s"%self.trans_win_type(win_type_list))
        self.game_over(uid, card, False, "put_win",self.trans_win_type(win_type_list))
        
        
    
    def getPutJokerScore(self,joker_put_count,joker_bar):
        logging.info(self,"getPutJokerScore================,",joker_put_count,",",joker_bar)
        score = 0
        if int(joker_put_count)==1:
            score = score+15
        elif int(joker_put_count)==2:
            score = score+45
        elif int(joker_put_count)==3:
            return 135
        #飞宝4个
        elif int(joker_put_count)==4:
            return 405
        #明杠宝
        if joker_bar and int(joker_bar)!=0:
            return 135
        return score
    
    def win(self, uid, data):
        if self.room['status'] != 'start':
            logging.error(u"该轮游戏已结束")
            return
        stop_pop_user = self.room['stop_pop_user']
        if not stop_pop_user:
            logging.error(u"目前没有提示, 不该%s操作,stop_pop_user=" %(uid,stop_pop_user))
            return
        elif stop_pop_user != uid:
            logging.error(u"玩家%s有提示, 不该%s操作" % (stop_pop_user, uid))
            return
        # card = data.get('card', '')
        
        p = Player(uid, self.bid, self.rid)
        current_card = p.current_card.members
        card = current_card[-1]
        # if not self.check_win(p, card):
        win_type_list = self.get_win_type(p,'')
        if not win_type_list:
            logging.error(u"请求错误,该用户不能胡牌:%s" % card)
            return
        self.room['stop_pop_user'] = ""
        self.room['stop_pop_act'] = ""
        member_len = len(self.members)
        
        dealer = self.room['dealer']
        #dealer_player = Player(dealer, self.bid, self.rid)
        #out_card = dealer_player.out_card.members
        
        joker = self.room['joker']
        if joker:
            joker_list = joker.split(",")
        else:
            joker_list = []
        
        jiazi = self.check_jiazi(p,card)
        logging.info(u"==================胡牌：是否为夹子%s"%jiazi)
        
        score = self.get_win_score(win_type_list) + self.getPutJokerScore(p.score["put_joker_count"], p.score["joker_bar"])
        if str(uid) == dealer:
            if not p.score['put_flag']:
                win_type_list.append("tianhu")
                score = score + self.get_win_score(['tianhu'])
        else:
            if self.room['bar_get_card'] == card:
                #杠上开花
                win_type_list.append("bar_win")
                score = score + self.get_win_score(['bar_win'])
            room_left_card = self.current_card.members
            if not room_left_card:
                #海底捞月
                win_type_list.append("haidi_win")
                score = score + self.get_win_score(['haidi_win'])
        if jiazi:
            win_type_list.append("jiazi")
            score = score + self.get_win_score(['haidi_win'])
            
        win_type_list = self.trans_win_type(win_type_list)
        logging.info(u"自模糊:%s" % str(win_type_list))
        every_lose_score = score
        win_score = score * (member_len - 1)
        logging.info(u"用户%s自摸胡牌,得%s分" % (uid, win_score))
        dark_bark_count = 0
        pair_bar_count = 0
        for member in self.members:
            player = Player(member, self.bid, self.rid)
            play_score = int(player.score['score'])
            if member != uid:
                play_score = int(play_score) - every_lose_score
                logging.info(u"用户%s自摸胡牌,中%s马,玩家各扣%s分" % (uid, 0, every_lose_score))
            
            #暗杠
            if player.dark_bar:
                play_score = play_score + 3*len(player.dark_bar)
                dark_bark_count = dark_bark_count + 1
            
            #碰杠
            pair_bar_user = player.pair_bar_user
            logging.info(u"碰杠：%s,==================="%player.pair_bar_user)
            if pair_bar_user:
                play_score = play_score + 3*len(player.pair_bar_user)
                pair_bar_count = pair_bar_count + 1
            
            #明杠
            white_bar = player.white_bar
            logging.info(u"明杠：%s,==================="%player.white_bar)
            if white_bar:
                play_score = play_score+len(player.white_bar)*1
                for wbu in player.bar_user:
                    white_bar_user = Player(wbu,self.bid,self.rid)
                    white_bar_user.score['score'] = int(white_bar_user.score['score']) - 1
                                           
            player.score['score'] = play_score
            
        #暗杠宝加减分
        dark_bar_joker_uid = self.room['dark_bar_joker_uid']
        if dark_bar_joker_uid:
            for member in self.members:
                player = Player(member,self.bid,self.rid)
                if member==dark_bar_joker_uid:
                    player['score'] = player['score'] + 60
                else:
                    player['score'] = player['score'] - 20
        
        p.score['score'] = int(p.score['score']) + win_score
        mid = self.incr_mid()
        for member in self.members:
            user = Player(member,self.bid,self.rid)
            logging.info(u"初始分：%s,碰杠数量：%s,暗杠数量：%s,pair_bar_count:%s,dark_bark_count:%s"%(user.score['score'],len(user.pair_bar_user),len(user.dark_bar),pair_bar_count,dark_bark_count))
            user.score['score'] = int(user.score['score']) - pair_bar_count*1 + len(user.pair_bar_user)*1 -dark_bark_count + len(user.dark_bar)
            nsq_pub({"b":self.bid, "u":str(member), "t":"game", "d":{"mid":mid, "act":"win", "card":card, "tips":[], "rid":self.rid, "uid":uid, "all_horse_card":[], "horse_card":[], "horse_num":0}})
        self.game_over(uid, card, win_type="win", win_type_list=win_type_list)
       
    def trans_win_type(self, win_type_list):
        res = []
        win_type_conf = {
                        'qingyise':{'name':u"清一色", 'score':4},
                         'qixiaodui':{'name':u"七对", 'score':4},
                         'two_qixiaodui':{'name':u"豪华七对", 'score':8},
                         'dtwo_qixiaodui':{'name':u"双豪华七对", 'score':16},
                         'three_qixiaodui':{'name':u"三豪华七对", 'score':32},
                         'yizhanghua':{'name':u"一张花", 'score':30},
                         'wuhuawugang':{'name':u"无花无杠", 'score':30},
                         'tianhu':{'name':u"天胡", 'score':10},
                         'dihu':{'name':u"地胡", 'score':10},
                         'pinghu':{'name':u"平胡", 'score':1},
                         'put_pinghu':{'name':u"德国牌", 'score':2},
                         'deguopai':{'name':u"德国牌", 'score':2},
                         'shisanlan':{'name':u'十三烂','score':4},
                         'jiazi':{'name':u'夹子','score':2},
                          'qixing':{'name':u'七星','score':8},
                          'haidi_win':{"score":4,"name":u"海底捞月"},
                          'bar_win':{"score":2,"name":u"杠上开花"}
                         }
        for win_type in win_type_list:
            res.append(win_type_conf[win_type]['name'])
        return res
    
    def get_win_score(self, win_type_list):
        score = 0
        win_type_conf = {                
                         'qingyise':{'name':u"清一色", 'score':4},
                         'qixiaodui':{'name':u"七对", 'score':4},
                         'two_qixiaodui':{'name':u"豪华七对", 'score':8},
                         'dtwo_qixiaodui':{'name':u"双豪华七对", 'score':16},
                         'three_qixiaodui':{'name':u"三豪华七对", 'score':32},
                         'yizhanghua':{'name':u"一张花", 'score':30},
                         'wuhuawugang':{'name':u"无花无杠", 'score':30},
                         'tianhu':{'name':u"天胡", 'score':10},
                         'dihu':{'name':u"地胡", 'score':10},
                         'pinghu':{'name':u"平胡", 'score':1},
                         'deguopai':{'name':u"德国牌", 'score':2},
                          'shisanlan':{'name':u'十三烂','score':4},
                          'jiazi':{'name':u'夹子','score':2},
                          'qixing':{'name':u'七星','score':8},
                          'haidi_win':{"score":4,"name":u"海底捞月"},
                          'bar_win':{"score":2,"name":u"杠上开花"},
                        
                         }
        win_type = win_type_list[0]
        return win_type_conf[win_type]['score']
    
    
    def game_over(self, winner='', card='',from_dissmiss=False, win_type="", win_type_list=[]):
        time.sleep(0.05)
        if from_dissmiss:
            from_dissmiss = "y"
        else:
            from_dissmiss = "n"
        
        db = dao.Game_DB()
        rules = {}
        #room_info = db.get_room(self.rid, self.bid)
        #gid = room_info.get("gid")
        gid = self.room['gid']
        if gid:
            rows = db.game_rule(gid)
        else:
            rows = db.room_rule(self.rid)
            gid = "0"
        for row in rows:
            k = row['param']
            v = row['value']
            rules[k] = v
        
        #比赛的牌局统一规则
        game_round = self.room['game_round']
        if not game_round:
            game_round = 1
        game_round = int(game_round)
        dealer = self.room['dealer']
        player_card = []
        for uid in self.members:
            if not uid:
                continue
            p = Player(uid, self.bid, self.rid)
            p_data = p.get_data()
            
            eat_list = []
            eat_data_list = p_data['eat']
            if eat_data_list:
                for eat_data in eat_data_list:
                    eat_list.append(eat_data.split(","))
                p_data['eat'] = eat_list
            
            del p_data['out_card']
            if dealer == uid:
                is_dealer = "y"
            else:
                is_dealer = "n"
            p_data['is_dealer'] = is_dealer
            player_card.append(p_data)
            
            # 重置玩家状态,和计算分数
            if not winner:
                score = 0
                p.score['score'] = 0
                p_data['score'] = "0"
            else:
                score = int(p_data['score'])
            db.update_player(self.rid, uid, score, 0)
            db.commit()
            player_info = db.get_player(self.rid, uid)
            p_data['user_score'] = player_info['score']
            
            if uid == winner:
                is_win = 1
            else:
                is_win = 0
            dark_bar = p_data['dark_bar']
            white_bar = p_data['white_bar']
            db.add_mj_room_log(0, gid, self.rid, game_round, uid, score, len(white_bar), len(dark_bar), 0, is_dealer, is_win, 0, '')
            db.commit()
        game_type = self.room['game_type']
        mid = self.incr_mid()
        all_room_card = self.current_card.members
        room_left_card = all_room_card
        for uid in self.members:
            if not uid:
                continue
            pub_data = {"b":self.bid, "u":str(uid), "t":"game", "d":{"win_type_list":win_type_list, "room_left_card":room_left_card, "match_id":0, "gid":gid, "rules":rules,
                                                                      "win_type":win_type,"from_dissmiss":from_dissmiss,"dealer":self.room['dealer'], "game_round":self.room['game_round'], 
                                                                      "player_card":player_card, "mid":mid, "act":"game_over", "winner":winner, "card":card, "rid":self.rid, "all_horse_card":[], 
                                                                      "horse_card":[], "horse_num":0}}
            nsq_pub(pub_data)
            db.save_game_over(self.rid, game_round, "game_over", uid, urllib.quote(json_encode(pub_data).encode("utf-8")))
            db.commit()
            try:
                if winner == uid:
                    win_round = 1
                else:
                    win_round = 0
                if db.has_user_stat(self.bid, uid, game_type):
                    db.update_user_stat(self.bid, uid, game_type, win_round)
                else:
                    db.add_user_stat(self.bid, uid, game_type, win_round, 0)
            except:
                logging.error(u"统计用户生涯错误:%s" % uid, exc_info=True)
        logging.info("game over")
        if winner:
            self.room['dealer'] = winner
        
        self.room['status'] = 'over'
        self.room['stop_pop_user'] = ''
        self.room['last_put_user'] = ''
        self.room['last_get_user'] = ''
        
        all_round = int(self.room['all_round'])
        db.game_over(self.rid, game_round)
        db.commit()
        self.room['game_round'] = game_round + 1
        if all_round <= game_round:
            self.dismiss(act='room_over')
     
    def get_win_type(self, player, card='', win_type='win'):
        n = 0
        dark_bar = player.dark_bar.members
        white_bar = player.white_bar.members
        pair = player.pair.members
        eat = player.eat.members
        n += len(dark_bar)
        n += len(white_bar)
        n += len(pair)
        n += len(eat)
        current_card = player.current_card.members
        if card:
            current_card.append(card)
        if len(current_card) != ((4 - n) * 3 + 2):
            logging.info(u"该玩家手牌相公不能胡牌:%s" % player.uid)
            return False
    
        joker = self.room['joker']
        if joker:
            joker_list = joker.split(",")
        else:
            joker_list = []
            
        all_card = []
        all_card.extend(current_card)
        if dark_bar:
            all_card.extend(dark_bar)
        if white_bar:
            all_card.extend(white_bar)
        if pair:
            all_card.extend(pair)
        if eat:
            for eat_card in eat:
                all_card.extend(eat_card.split(","))
        qingyise = self.is_qingyise(all_card)
        if qingyise:
            if self.is_pinghu(current_card, n, win_type, joker_list):
                return ['qingyise']
        #七小队
        qixiaodui = self.check_seven_pairs(current_card,joker_list)
        logging.info("胡牌，是否为七对：%s",qixiaodui)
        if qixiaodui:
            four_card_cnt = self.get_seven_pairs_type(current_card, joker_list)
            if four_card_cnt==1:
                return ['two_qixiaodui']
            elif four_card_cnt==2:
                return ['dtwo_qixiaodui']
            elif four_card_cnt==3:
                return ['three_qixiaodui']
            return ["qixiaodui"]
        shisanlan = self.check_shisanlan(current_card, joker_list)
        if shisanlan:
            if self.check_qixing(current_card,joker_list):
                return ['qixing']
            return ["shisanlan"]
        pinghu = self.is_pinghu(current_card, n, win_type, joker_list)
        if not pinghu:
            logging.info(u"胡牌错误:%s,手牌：%s,n:%s,win_type:%s，joker_list:%s" %(pinghu,current_card,n,win_type,joker_list))
            return False
        joker_count = current_card.count(joker)
       
        if joker_count>=1:
            return ['pinghu']
        else:
            return ['deguopai']
        
           
    def dismiss(self, act='room_over'):
        #time.sleep(0.5)
        db = dao.Game_DB()
        player_data = {}
        player_stat = []
        if not self.room['status']:
            logging.info(u"房间结束,未开始:%s" % self.rid)
            deduct_flag = False
            winner = ""
            for uid in self.members:
                player_stat.append({"uid":uid,"horse":0,"dark_bar":0,"white_bar":0,"score":0,"win_num":0})
        else:
            p_stat = db.player_stat(self.rid)
            for ps in p_stat:
                ps['horse'] = int(ps['horse'])
                ps['dark_bar'] = int(ps['dark_bar'])
                ps['white_bar'] = int(ps['white_bar'])
                ps['score'] = int(ps['score'])
                ps['win_num'] = int(ps['win_num'])
                
                ps['max_score'] = int(ps['max_score'])
                ps['lose_num'] = int(ps['lose_num'])
                ps['bomb'] = int(ps['dark_bar'])
                player_data[str(ps['uid'])] = ps
            deduct_flag = True
            if p_stat:
                winner = p_stat[-1]['uid']
            else:
                winner = ""
            # 排序最后一家为大赢家
            player_stat = p_stat
         
        room_info = db.get_room(self.rid, self.bid)
        admin = room_info['admin']
        match_id = room_info['mid']
        gid = room_info['gid']
        if not gid:
            gid = 0
        for ps in player_stat:
            if ps['uid'] == winner:
                is_winner = 'y'
            else:
                is_winner = 'n'
            db.add_room_stat(match_id, gid, self.rid, ps['uid'], ps['score'], is_winner)
            db.commit()
        if not match_id:
            #比赛的房间不发送room_over
            for uid in self.members:
                if not uid:
                    continue
                pub_data = {"b":self.bid, "u":str(uid), "t":"game", "d":{"act":"room_over", "rid":self.rid, "player_stat":player_stat, "winner":winner, "admin":admin}}
                db.save_game_over(self.rid, 0, "room_over", uid, json_encode(pub_data))
                db.commit()
                nsq_pub(pub_data)
                
        else:
            #比赛房间不扣房卡
            deduct_flag = False
        db.dismiss_room(self.rid)
        db.commit()
        game_type = self.room['game_type']
        #gid = self.room['gid']
        if match_id or gid:
            nsq_pub({"b":self.bid, "u":"", "t":"game", "d":{"game_type":game_type, "match_id":match_id, "gid":gid, "act":"room_over", "rid":self.rid, "player_stat":player_stat, "winner":winner, "admin":admin}}, "match_club")
            
        #if deduct_flag:
        #    card = room_info['card']
        #    db.deduct_card(self.bid, admin, card)
        #    db.commit()
        #    nsq_pub({"act":"deduct_card", "bid":self.bid, "uid":admin, "card":card, "rid":self.rid}, "total")
        #    logging.info(u"房间%s解散成功,扣除房卡, bid:%s,uid:%s,card:%s" % (self.rid, self.bid, admin, card))
        #else:
        #    logging.info(u"房间%s解散成功,游戏无需扣房卡" % self.rid)
        for member in self.members:
            member_player = Player(member, self.bid, self.rid)
            member_player.clear()
        redisco.connection.delete("r:%s:current_card" % self.rid)
        redisco.connection.delete("r:%s:out_card" % self.rid)
        redisco.connection.delete("r:%s" % self.rid)
        redisco.connection.delete("r:%s:mid" % self.rid)
        redisco.connection.delete("r:%s:p" % self.rid)    
               
class Player():
    def __init__(self, uid, bid='', rid='', first=False):
        self.uid = uid
        self.bid = bid
        self.rid = rid
        if first:
            redisco.connection.delete("p:%s:%s:%s:current_card" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s:out_card" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s:dark_bar" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s:white_bar" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s:pair" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s:eat" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s:tips" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s:bar_user" % (bid, uid, rid))
            redisco.connection.delete("p:%s:%s:%s:pair_bar_user" % (bid, uid, rid))
            
            self.score = Hash("p:%s:%s:%s" % (bid, uid, rid))
            self.score['score'] = 0
            self.score['win_score'] = 0
            self.score['put_flag'] = ''
            self.score['win_type'] = ''
            self.score['win_type_name'] = ''
            self.score['win_card'] = ''
            self.score['put_joker_count'] = 0
            self.score['joker_bar'] = 0
        else:
            self.score = Hash("p:%s:%s:%s" % (bid, uid, rid))
        self.current_card = List("p:%s:%s:%s:current_card" % (bid, uid, rid))
        self.out_card = List("p:%s:%s:%s:out_card" % (bid, uid, rid))
        self.dark_bar = List("p:%s:%s:%s:dark_bar" % (bid, uid, rid))
        self.white_bar = List("p:%s:%s:%s:white_bar" % (bid, uid, rid))
        self.bar_user = List("p:%s:%s:%s:bar_user" % (bid, uid, rid))
        self.pair_bar_user = List("p:%s:%s:%s:pair_bar_user" % (bid, uid, rid))
        self.pair = List("p:%s:%s:%s:pair" % (bid, uid, rid))
        self.eat = List("p:%s:%s:%s:eat" % (bid, uid, rid))
        self.tips = List("p:%s:%s:%s:tips" % (bid, uid, rid))

    def clear(self):
        redisco.connection.delete("p:%s:%s:%s:current_card" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s:out_card" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s:dark_bar" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s:white_bar" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s:pair" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s:eat" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s:tips" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s:bar_user" % (self.bid, self.uid, self.rid))
        redisco.connection.delete("p:%s:%s:%s:pair_bar_user" % (self.bid, self.uid, self.rid))
        
    def get_data(self):
        return {"uid":self.uid,
                "current_card":self.current_card.members,
                "out_card":self.out_card.members,
                "dark_bar":self.dark_bar.members,
                "white_bar":self.white_bar.members,
                "pair":self.pair.members,
                "eat":self.eat.members,
                "score":self.score['score'],
                "win_card":self.score['win_card'],
                }
    
'''麻将户牌检测'''
class MaJiangCheck():
    def __init__(self):
        self._res = []
        self.joker_list = []
    
    def all_combination(self, all_card, card, joker_list=[]):
        print  "card",card,"==all_card:",all_card,"==joker_list",joker_list
        c_1 = card - 1
        c_2 = card - 2
        c1 = card + 1
        c2 = card + 2
        res = []
        if all_card.count(card) >= 2:
            res.append([card, card])
        if card < 40:
            j_n = len(joker_list)
            if c1 % 10 <= 8 and c2%10 <=9 and c2/10 == card/10:
                if c1 in all_card and c2 in all_card:
                    res.append([c1, c2])
                elif c1 in all_card and j_n >= 1:
                    res.append([c1, joker_list[0]])
                elif c2 in all_card and j_n >= 1:
                    res.append([c2, joker_list[0]])
            if c_1 % 10 >0 and c1 % 10 <=9 and c_1/10 == card/10 and c1/10==card/10:
                if c1 in all_card and c_1 in all_card:
                    res.append([c_1, c1])
                elif c1 in all_card and j_n >= 1:
                    res.append([c1, joker_list[0]])
                elif c_1 in all_card and j_n >= 1:
                    res.append([c_1, joker_list[0]])
            if c_1 % 10 >0 and c_2 % 10 >0 and c_2/10 == card/10 and c_1/10==card/10:
                if c1 in all_card and c_1 in all_card:
                    res.append([c_1, c_2])
                elif c1 in all_card and j_n >= 1:
                    res.append([c_1, joker_list[0]])
                elif c_1 in all_card and j_n >= 1:
                    res.append([c_2, joker_list[0]])
            
        if all_card.count(card) == 1 and len(joker_list) >= 1:
            res.append([card, joker_list[0]])
        elif len(joker_list) >= 2:
            res.append([joker_list[0], joker_list[1]])
        return res
    
    def card_group(self, all_card, pre='', joker_list=[]):
        card_list = self.trans_card(all_card)
        if not card_list:
            return self._res
        c = card_list.pop(0)
        all_group = self.all_combination(card_list, c, joker_list)
        print "#######################",all_group
        if not all_group:
            return self.card_group(card_list, pre, joker_list)
        for group in all_group:
            tmp = pre
            card_copy = copy.deepcopy(card_list)
            joker_copy = copy.deepcopy(joker_list)
            g1 = group[0]
            g2 = group[1]
            if g1 in card_copy:
                card_copy.remove(g1)
            elif g1 in joker_copy:
                joker_copy.remove(g1)
            else:
                break
            if g2 in card_copy:
                card_copy.remove(g2)
            elif g2 in joker_copy:
                joker_copy.remove(g2)
            else:
                break
            
            tmp += "%s,%s,%s_" % (c, g1, g2)
            self._res.append(tmp)
            self.card_group(card_copy, tmp, joker_copy)
        return self._res
        
    def card_group_merge(self, all_card):
        card_list = self.trans_card(all_card)
        tmp_result = []
        for group in self._res:
            if group.endswith("_"):
                group = group[:-1]
            rows = group.split("_")
            if len(rows) > len(tmp_result):
                tmp_result = rows
        res = []
        for row in tmp_result:
            seq = []
            for x in row.split(","):
                if int(x) in card_list:
                    card_list.remove(int(x))
                seq.append(int(x))
            res.append(seq)
        self._res = []
        return res, card_list

    def trans_card(self, all_card):
        return sorted([int(x) for x in all_card])
    
    def get_jiang(self, card, joker_list=[]):
        r = []
        for k in set(card):
            if card.count(k) >= 2 or joker_list:
                r.append(k)
        r.sort()
        return r
    
    def count_group(self, all_card, jiang):
        n = 0
        res = []
        card_list = self.trans_card(all_card)
        if card_list.count(jiang) < 2:
            card_list.remove(jiang)
            if self.joker_list:
                self.joker_list.pop()
            else:
                return 0, []
        else:
            card_list.remove(jiang)
            card_list.remove(jiang)
        n += 1
        left_card = []
        card_list.sort()
        joker_list = copy.deepcopy(self.joker_list)
        self.card_group(card_list, '', joker_list)
        seq, left_card = self.card_group_merge(card_list)
        n += len(seq)
        return n, left_card
    
    def check_win(self, n, current_card, card='', joker=[]):
        if card:
            current_card.append(card)
        current_card = self.trans_card(current_card)
        joker = self.trans_card(joker)
        joker_list = []
        for j in joker:
            j_n = current_card.count(j)
            joker_list.extend([j]*j_n)
            for i in range(j_n):
                current_card.remove(j)
        jiang_list = self.get_jiang(current_card, joker_list)
        for jiang in jiang_list:
            all_joker = copy.deepcopy(joker_list)
            self.joker_list = all_joker
            allcard = self.trans_card(current_card)
            logging.info("将==========",jiang)
            group_n, left_card = self.count_group(allcard, jiang)
            if not left_card and group_n + n >= 5 :
                return True
        return False
    
 
def json_encode(data):
    return json.dumps(data, separators=(',', ':'))

def nsq_pub(message, topic='response'):
    try:
        nsq_client = nsqd.Client("http://%s/" % config.NSQ_HTTP)
        logging.info(u"推送消息:%s" % message)
        if isinstance(message, dict):
            message = json_encode(message)
        #logging.info(u"推送消息:%s" % message)
        nsq_client.pub(topic, message)
        return True
    except:
        logging.error("nsq send error", exc_info=True)
        return False
    
def get_last_data(bid, uid, rid):
    user_info = Hash("%s_%s" % (bid, uid))
    rid = user_info['rid']
    room = Hash("r:%s" % rid)
    tdh = YgMajiang(rid, bid)
    last_get_user = tdh.room['last_get_user']
    last_put_user = tdh.room['last_put_user']
    joker = tdh.room['joker']
    logging.info('joker=======',joker,"==rid==",rid,"===uid=--",uid)
    pubdata = {'act':'get_last_data', "joker":joker,'rid':rid, 'last_player':last_get_user, 'last_put_user':last_put_user}
    all_player_data = []
    l = List("r:%s:p" % rid)
    members = l.members
    for member in members:
        p = Player(member, bid, rid)
        player_data = p.get_data()
        eat_list = []
        eat_data_list = player_data['eat']
        for eat_data in eat_data_list:
            eat_list.append(eat_data.split(","))
        player_data['eat'] = eat_list
        if member != uid:
            player_data['current_card'] = ["*"] * len(player_data['current_card'])
            #player_data['dark_bar'] = ["*"] * len(player_data['dark_bar'])
        player_data['status'] = 1
        all_player_data.append(player_data)
    tips = []
    dark_bar = []
    eat_card = []
    last_put_card = ''
    stop_pop_user = tdh.room['stop_pop_user']
    
    if stop_pop_user == str(uid):
            tips = tdh.room['stop_pop_act'].split(",")
            if tips:
                p = Player(uid, bid, rid)
                current_card = p.current_card.members
                if 'dark_bar' in tips:
                    dark_bar = tdh.check_init_dark_bar(current_card)
                if "eat" in tips:
                    last_put_player = Player(last_put_user, bid, rid)
                    last_put_card = last_put_player.out_card.members[-1]
                    eat_card = tdh.get_eat_card(current_card, last_put_card)
                if "bar_win" in tips:
                    tips.extend(['pair_bar_win'])
    pubdata["eat_card"] = eat_card
    pubdata["dark_bar"] = dark_bar
    pubdata["left_card"] = len(tdh.current_card)
    pubdata["card"] = last_put_card
    dealer = tdh.room['dealer']
    if not dealer:
        dealer = ''
    pubdata["dealer"] = dealer 
    pubdata["tips"] = tips
    pubdata["all_player_data"] = all_player_data
    pubdata["game_round"] = room['game_round']
    pubdata["all_round"] = room['all_round']
    pubdata["status"] = room['status']
    nsq_pub({'u':str(uid), 'b':bid, 't':'game', 'd':pubdata})
    
# def get_last_data(bid, uid, rid):
#     all_player_data = []
#     mj = YgMajiang(rid, bid)
#     for member in mj.members:
#         p = Player(member, bid, rid)
#         player_data = p.get_data()
#         eat_list = []
#         eat_data_list = player_data['eat']
#         for eat_data in eat_data_list:
#             eat_list.append(eat_data.split(","))
#         player_data['eat'] = eat_list
#         player_data['status'] = 1
#         all_player_data.append(player_data)
#     game_round = mj.room['game_round']
#     all_round = mj.room['all_round']
#     dealer = mj.room['dealer']
#     status = mj.room['status']
#     last_get_user = mj.room['last_get_user']
#     last_put_user = mj.room['last_put_user']
#     if last_put_user:
#         last_player = last_put_user
#     else:
#         last_player = last_get_user
#     last_card = mj.room['last_card']
#     left_card = len(mj.current_card.members)
#     pub_data = {"act":"get_last_data",
#                 "game_round":game_round, 
#                 "all_round":all_round, 
#                 "last_card":last_card, 
#                 "last_player":last_player,
#                 "left_card":left_card,
#                 "dealer":dealer,
#                 "joker":mj.room['joker'],
#                 "status":status,
#                 "rid":rid,
#                 "all_player_data":all_player_data,
#                 }
#    
#     tips_user = mj.tips_user
#     if tips_user:
#         if uid in tips_user:
#             p = Player(uid, bid, rid)
#             tips = p.tips.members
#             eat_card_list = []
#             bar_card = []
#             if "dark_bar" in tips:
#                 bar_card = mj.check_init_dark_bar(p.current_card.members)
#             elif "eat" in tips:
#                 eat_card_list = mj.get_eat_card(p.current_card.members, last_card)
#             #mj.notify_tips(uid, last_card, tips, bar_card, eat_card_list,[])
#             pub_data['eat_card'] = eat_card_list
#             pub_data['bar_card'] = bar_card
#             pub_data['tips'] = tips
#     nsq_pub({"b":bid, "u":uid, "t":"game", "d":pub_data})
#     if tips_user==False:
#         nsq_pub({"b":bid, "u":uid, "t":"game", "d":{"act":"turn_put", "rid":rid, "uid":last_player}})
        
    